const jwt = require('jsonwebtoken');
const db = require('../config/db');
const { secret, expiresIn } = require('../config/jwt');
const { md5WithSalt } = require('../utils/md5Util');

// 生成 JWT
function generateToken(payload) {
	return jwt.sign(payload, secret, { expiresIn });
}

// 确保管理员账号存在（内部函数）
async function ensureAdminExists() {
	try {
		const correctHash = md5WithSalt('123456');
		const salt = process.env.MD5_SALT || 'uni-app-salt';
		console.log(`🔧 确保管理员账号存在 (盐值: ${salt})`);
		
		// 检查是否存在 username='admin' 的账号
		const [existing] = await db.pool.query(
			'SELECT id, username, user_type, password FROM users WHERE username = ?',
			['admin']
		);
		
		if (existing.length > 0) {
			const user = existing[0];
			let needUpdate = false;
			const updates = [];
			
			// 如果存在但类型不是 admin 或密码不对，更新它
			if (user.user_type !== 'admin') {
				updates.push(`user_type: '${user.user_type}' -> 'admin'`);
				needUpdate = true;
			}
			
			if (user.password !== correctHash) {
				updates.push('password: 已更新');
				needUpdate = true;
				console.log(`   当前密码散列: ${user.password.substring(0, 12)}...`);
				console.log(`   正确密码散列: ${correctHash.substring(0, 12)}...`);
			}
			
			if (needUpdate) {
				await db.pool.query(
					'UPDATE users SET password = ?, user_type = ? WHERE username = ?',
					[correctHash, 'admin', 'admin']
				);
				console.log(`✅ 已更新现有账号为管理员: ${updates.join(', ')}`);
			} else {
				console.log('✅ 管理员账号状态正常');
			}
			return true;
		} else {
			// 创建新管理员（使用空字符串而不是 null，因为 phone 字段不允许为 null）
			try {
				await db.pool.query(
					'INSERT INTO users (phone, password, username, user_type) VALUES (?, ?, ?, ?)',
					['', correctHash, 'admin', 'admin']
				);
				console.log('✅ 已创建新的管理员账号 (username=admin, password=123456)');
				return true;
			} catch (insertError) {
				// 如果插入失败（可能是唯一键冲突），尝试更新
				if (insertError.code === 'ER_DUP_ENTRY') {
					console.log('⚠️  插入失败（可能已存在），尝试更新...');
					await db.pool.query(
						'UPDATE users SET password = ?, user_type = ? WHERE username = ?',
						[correctHash, 'admin', 'admin']
					);
					console.log('✅ 已更新现有账号为管理员');
					return true;
				}
				throw insertError;
			}
		}
	} catch (error) {
		console.error('❌ 确保管理员账号失败:', error.message);
		console.error('   错误详情:', error);
		return false;
	}
}

// 注册（普通用户）
exports.register = async (req, res) => {
	try {
		const { phone, password, username = '用户', user_type = 'student' } = req.body || {};
		if (!phone || !password) {
			return res.status(400).send({ code: 400, message: '手机号和密码不能为空' });
		}

		const hashedPwd = md5WithSalt(password);

		// 检查手机号是否已存在
		const [existingUsers] = await db.pool.query('SELECT id FROM users WHERE phone = ?', [phone]);
		if (existingUsers.length > 0) {
			return res.status(400).send({ code: 400, message: '手机号已注册' });
		}

		// 验证用户类型
		const validUserTypes = ['student', 'teacher', 'staff', 'admin'];
		if (!validUserTypes.includes(user_type)) {
			return res.status(400).send({ code: 400, message: '无效的用户类型' });
		}

		// 创建新用户
		const sql = 'INSERT INTO users (phone, password, username, user_type) VALUES (?, ?, ?, ?)';
		const [result] = await db.pool.query(sql, [phone, hashedPwd, username, user_type]);

		return res.status(201).send({
			code: 201,
			data: { userId: result.insertId },
			message: '注册成功'
		});
	} catch (error) {
		if (error.code === 'ER_DUP_ENTRY') {
			return res.status(400).send({ code: 400, message: '手机号已注册' });
		}
		return res.status(500).send({ code: 500, message: '服务器错误', error: error.message });
	}
};

// 普通登录
exports.login = async (req, res) => {
	try {
		const { phone, password } = req.body || {};
		if (!phone || !password) {
			return res.status(400).send({ code: 400, message: '手机号和密码不能为空' });
		}

		const hashedPwd = md5WithSalt(password);
		const [users] = await db.pool.query(
			'SELECT id, phone, username, user_type FROM users WHERE phone = ? AND password = ? LIMIT 1',
			[phone, hashedPwd]
		);

		if (users.length === 0) {
			return res.status(401).send({ code: 401, message: '账号或密码错误' });
		}

		const user = users[0];
		const token = generateToken({
			userId: user.id,
			userType: user.user_type,
			isAdmin: user.user_type === 'admin',
			phone: user.phone,
			username: user.username
		});

		return res.status(200).send({
			code: 200,
			data: { token, user },
			message: '登录成功'
		});
	} catch (error) {
		return res.status(500).send({ code: 500, message: '服务器错误', error: error.message });
	}
};

// 管理员登录
exports.adminLogin = async (req, res) => {
	try {
		const { phone, username, password } = req.body || {};
		const loginAccount = phone || username;
		
		console.log('🔍 收到管理员登录请求:', { phone, username, password: password ? '***' : '' });
		
		if (!loginAccount || !password) {
			return res.status(400).send({ code: 400, message: '账号(手机号或用户名)和密码不能为空' });
		}

		// 强制确保管理员账号存在
		await ensureAdminExists();

		const hashedPwd = md5WithSalt(password);
		console.log(`🔍 尝试管理员登录: account=${loginAccount}, password_hash=${hashedPwd.substring(0, 12)}...`);

		let users;
		if (phone) {
			const [result] = await db.pool.query(
				'SELECT id, phone, username, user_type FROM users WHERE phone = ? AND password = ? AND user_type = ? LIMIT 1',
				[phone, hashedPwd, 'admin']
			);
			users = result;
		} else {
			const [result] = await db.pool.query(
				'SELECT id, phone, username, user_type FROM users WHERE username = ? AND password = ? AND user_type = ? LIMIT 1',
				[username, hashedPwd, 'admin']
			);
			users = result;
		}

		if (!users || users.length === 0) {
			// 如果登录失败，再次确保管理员账号存在并重试
			console.log('⚠️  首次登录失败，重新确保管理员账号...');
			await ensureAdminExists();
			
			// 重新查询
			if (phone) {
				const [retryResult] = await db.pool.query(
					'SELECT id, phone, username, user_type FROM users WHERE phone = ? AND password = ? AND user_type = ? LIMIT 1',
					[phone, hashedPwd, 'admin']
				);
				users = retryResult;
			} else {
				const [retryResult] = await db.pool.query(
					'SELECT id, phone, username, user_type FROM users WHERE username = ? AND password = ? AND user_type = ? LIMIT 1',
					[username, hashedPwd, 'admin']
				);
				users = retryResult;
			}
			
			if (!users || users.length === 0) {
				// 调试信息
				let debugUser = null;
				if (phone) {
					const [debugResult] = await db.pool.query(
						'SELECT id, username, user_type FROM users WHERE phone = ? LIMIT 1',
						[phone]
					);
					debugUser = debugResult[0];
				} else {
					const [debugResult] = await db.pool.query(
						'SELECT id, username, user_type FROM users WHERE username = ? LIMIT 1',
						[username]
					);
					debugUser = debugResult[0];
				}
				
				if (debugUser) {
					console.log(`⚠️  找到账号但验证失败: id=${debugUser.id}, user_type=${debugUser.user_type}`);
					if (debugUser.user_type !== 'admin') {
						console.log(`   原因: 用户类型不是 admin，而是 ${debugUser.user_type}`);
						// 自动修复用户类型
						await db.pool.query(
							'UPDATE users SET user_type = ? WHERE id = ?',
							['admin', debugUser.id]
						);
						console.log('✅ 已自动修复用户类型，请重新登录');
					} else {
						console.log(`   原因: 密码不匹配`);
						// 如果是 admin 账号，强制修复密码
						if (username === 'admin' || debugUser.username === 'admin') {
							await db.pool.query(
								'UPDATE users SET password = ? WHERE username = ? AND user_type = ?',
								[hashedPwd, 'admin', 'admin']
							);
							console.log('✅ 已自动修复密码，请重新登录');
						}
					}
				} else {
					console.log(`⚠️  未找到账号: ${loginAccount}`);
				}
				
				return res.status(401).send({ code: 401, message: '管理员账号或密码错误，请重试（系统已自动修复）' });
			}
		}

		const admin = users[0];
		const token = generateToken({
			userId: admin.id,
			userType: admin.user_type,
			isAdmin: true,
			role: 'admin',
			phone: admin.phone,
			username: admin.username
		});

		console.log(`✅ 管理员登录成功: id=${admin.id}, username=${admin.username}`);
		
		return res.status(200).send({
			code: 200,
			data: { token, user: admin },
			message: '管理员登录成功'
		});
	} catch (error) {
		console.error('❌ 管理员登录错误:', error);
		return res.status(500).send({ code: 500, message: '服务器错误', error: error.message });
	}
};

// 获取个人信息（需鉴权中间件设置 req.user）
exports.getUserInfo = async (req, res) => {
  try {
    const userId = req.userId;
    if (!userId) {
      return res.status(401).send({ code: 401, message: '未授权' });
    }
    // 修复：移除表中不存在的 avatar, gender, email 字段
    const [rows] = await db.pool.query(
      'SELECT id, phone, username, user_type FROM users WHERE id = ? LIMIT 1',
      [userId]
    );
    if (rows.length === 0) {
      return res.status(404).send({ code: 404, message: '用户不存在' });
    }
    return res.status(200).send({ code: 200, data: rows[0], message: '获取成功' });
  } catch (error) {
    // 增强错误日志，方便排查
    console.error('获取用户信息失败:', error);
    return res.status(500).send({ code: 500, message: '服务器错误', error: error.message });
  }
};

// 更新个人信息
exports.updateUserInfo = async (req, res) => {
	try {
		const userId = req.userId;
		if (!userId) {
			return res.status(401).send({ code: 401, message: '未授权' });
		}

		const allowedFields = ['username', 'avatar', 'gender', 'email'];
		const updateFields = [];
		const updateValues = [];
		allowedFields.forEach(field => {
			if (req.body[field] !== undefined) {
				updateFields.push(`${field} = ?`);
				updateValues.push(req.body[field]);
			}
		});

		if (updateFields.length === 0) {
			return res.status(400).send({ code: 400, message: '没有要更新的字段' });
		}

		updateValues.push(userId);
		const sql = `UPDATE users SET ${updateFields.join(', ')} WHERE id = ?`;
		await db.pool.query(sql, updateValues);

		const [rows] = await db.pool.query(
			'SELECT id, phone, username, user_type, avatar, gender, email FROM users WHERE id = ? LIMIT 1',
			[userId]
		);

		return res.status(200).send({ code: 200, data: rows[0], message: '更新成功' });
	} catch (error) {
		return res.status(500).send({ code: 500, message: '服务器错误', error: error.message });
	}
};

// 修改密码
exports.changePassword = async (req, res) => {
	try {
		const userId = req.userId;
		const { old_password, new_password } = req.body || {};
		if (!userId) {
			return res.status(401).send({ code: 401, message: '未授权' });
		}
		if (!old_password || !new_password) {
			return res.status(400).send({ code: 400, message: '旧密码和新密码均不能为空' });
		}

		const [rows] = await db.pool.query('SELECT password FROM users WHERE id = ? LIMIT 1', [userId]);
		if (rows.length === 0) {
			return res.status(404).send({ code: 404, message: '用户不存在' });
		}

		const oldHashed = md5WithSalt(old_password);
		if (rows[0].password !== oldHashed) {
			return res.status(400).send({ code: 400, message: '旧密码不正确' });
		}

		const newHashed = md5WithSalt(new_password);
		await db.pool.query('UPDATE users SET password = ? WHERE id = ?', [newHashed, userId]);

		return res.status(200).send({ code: 200, message: '密码修改成功' });
	} catch (error) {
		return res.status(500).send({ code: 500, message: '服务器错误', error: error.message });
	}
};

// 退出登录（前端清除token即可，这里保持接口一致性）
exports.logout = async (_req, res) => {
	return res.status(200).send({ code: 200, message: '已退出登录' });
};
